package test;

class Node {
    int value;
    Node left;
    Node right;

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    //添加节点的方法
    //递归的形式添加节点，注意需要满足二叉排序树的眼球
    public void add(Node node) {
        if (node == null) {
            return;
        }
        //判断传入的节点的值，和当前子树的根节点的值关系
        if (node.value < this.value) {
            //如果当前节点左子节点为null
            if (this.left == null) {
                this.left = node;
            } else {
                //递归的先向左子树添加
                this.left.add(node);
            }
        } else {
            if (this.right == null) {
                this.right = node;
            } else {
                //递归的向右子树添加
                this.right.add(node);
            }
        }
    }

    //查找需要删除的节点
    public Node searchNode(int value) {//value希望删除的值，找到了返回节点，没找到返回null
        if (value == this.value) {
            return this;
        } else if (value < this.value) {//需要查找的比当前的数小，需要向左子树找
            //左子节点为空
            if (this.left == null) {
                return null;
            }
            return this.left.searchNode(value);
        } else {
            if (this.right == null) {
                return null;
            }
            return this.right.searchNode(value);
        }
    }

    //查找需要删除节点的父节点
    public Node searchparent(int value) {//value希望删除的值的节点，找到了返回节点，没找到返回null
        if ((this.left != null && this.left.value == value) || (this.right != null && this.right.value == value)) {
            return this;
        } else {
            //如果当前查找的值小于当前节点的值，并且当前节点的左子节点为空
            if (this.left != null && value < this.value) {
                return this.left.searchparent(value);
            } else if (this.right != null && value >= this.value) {
                return this.right.searchparent(value);
            } else {
                return null;//没有找到父节点
            }
        }
    }

    //前序遍历
    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }

    //中序遍历
    public void midOrder() {
        if (this.left != null) {
            this.left.midOrder();
        }
        System.out.println(this);
        if (this.right != null) {
            this.right.midOrder();
        }
    }

    //后序遍历
    public void laterOrder() {
        if (this.left != null) {
            this.left.laterOrder();
        }
        if (this.right != null) {
            this.right.laterOrder();
        }
        System.out.println(this);
    }
}